﻿using System;
using System.Collections.Generic;
using System.Text;

namespace SharpSoft
{
    /// <summary>
    /// 提供一组缓存的键值对用于储存用户的配置
    /// </summary>
    public abstract class ConfigBase
    {

        public ConfigBase()
        { 
        }

        public string this[string key]
        {
            get { return this.Get(key); }
            set { this.Set(key, value); }
        }

        private bool isInited = false;
        private readonly object asyncState = new object();
        protected Dictionary<string, string> buffer = new Dictionary<string, string>();//配置缓存
        /// <summary>
        /// 获取配置
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public string Get(string key)
        {
            lock (asyncState)
            {
                if (!isInited)
                {
                    this.OnInit();
                    this.isInited = true;
                }

                if (buffer.ContainsKey(key))
                {
                    return buffer[key];
                }
                else
                {
                    this.OnLoadValue(key);
                    if (buffer.ContainsKey(key))
                    {
                        return buffer[key];
                    }
                    else
                    {
                        return null;
                    }

                }
            }

        }
        /// <summary>
        /// 设置配置值
        /// </summary>
        /// <param name="key"></param>
        public void Set(string key, string value)
        {
            lock (asyncState)
            {
                if (buffer.ContainsKey(key))
                {
                    buffer[key] = value;
                }
                else
                {
                    buffer.Add(key, value);
                }
                this.OnSaveValue(key, value);
            }
        }
        /// <summary>
        /// 初始化读取所有配置
        /// </summary>
        protected abstract void OnInit();
        /// <summary>
        /// 加载值
        /// </summary>
        /// <param name="key"></param>
        protected abstract void OnLoadValue(string key);
        /// <summary>
        /// 保存值
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        protected abstract void OnSaveValue(string key, string value);
    }
}
